package hello;

import com.orbitz.consul.AgentClient;
import com.orbitz.consul.Consul;
import com.orbitz.consul.NotRegisteredException;
import com.orbitz.consul.config.ClientConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import javax.annotation.PreDestroy;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class Application {
    private static final Logger logger = LogManager.getLogger(Application.class);
    private static final String serviceId = "ttranslateId";
    private static AgentClient agentClient;

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
        logger.warn("socode: Application run!");

        // connect to Consul on localhost
        Consul consul = Consul.builder()
            .withUrl("http://consul.ys111.top:8500")
            .withAclToken("7158eb08-10f2-9826-c232-0f90a8d60386")
            .build();
        agentClient = consul.agentClient();
        // registers with a TTL of 11 seconds
        agentClient.register(5416, 15L, "ttranslate", serviceId, Collections.emptyList(), Collections.emptyMap());
        ConsulHealthCheck();
    }

    private static void ConsulHealthCheck() {
        try {
            while (true) {
                agentClient.pass(serviceId);
                TimeUnit.SECONDS.sleep(10);
            }
        } catch (NotRegisteredException ne) {
            logger.error("NotRegisteredException", ne);
        } catch (InterruptedException ie) {
            logger.error("InterruptedException", ie);
        }
    }
}